package com.jiaquyun.jcyx.main

import android.os.Bundle
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ConvertUtils
import com.jiaquyun.jcyx.R
import com.jiaquyun.jcyx.app.AppConstance
import com.jiaquyun.jcyx.app.JCApplication
import com.jiaquyun.jcyx.entity.CartAction
import com.jiaquyun.jcyx.entity.CartGoods
import com.jiaquyun.jcyx.entity.UserShops
import com.jiaquyun.jcyx.main.goods.adapter.GoodsCartAdapter
import com.jiaquyun.jcyx.jetpack.mode.CartViewModel
import com.jiaquyun.jcyx.main.cart.CartSettlementActivity
import com.jiaquyun.jcyx.main.goods.GoodsDetailsActivity
import com.jiaquyun.jcyx.main.mine.MineShopsActivity
import com.module.lemlin.LoadingDialog
import com.module.lemlin.custom.SpacingItemDecoration
import com.module.lemlin.http.Status
import com.module.lemlin.http.msg
import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.fragment_main_cart.*
import kotlinx.android.synthetic.main.include_home_bar.*
import java.text.DecimalFormat

class MainCartFragment : OwnerViewModeFragment<CartViewModel>() {

    companion object {
        fun newInstance(): MainCartFragment {
            return MainCartFragment()
        }
    }

    private val goodsCartAdapter: GoodsCartAdapter = GoodsCartAdapter()

    override val layoutResId: Int
        get() = R.layout.fragment_main_cart

    override fun viewModel(): CartViewModel {
        return createViewModel()
    }

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(clCartBar)


        rvCartGoodsBody.apply {
            itemAnimator?.changeDuration = 0
            val decoration = SpacingItemDecoration(
                vGap = ConvertUtils.dp2px(13f),
                hGap = ConvertUtils.dp2px(13f)
            )
            addItemDecoration(decoration)
        }.adapter = goodsCartAdapter

        goodsCartAdapter.setOnItemChildClickListener { _, view, position ->
            val itemData: CartGoods = goodsCartAdapter.getItem(position)
            when (view.id) {
                R.id.cbGoodsCartOpt -> {
                    val cartAction = CartAction(
                        cartId = itemData.cart_id,
                        isSelected = (view as CheckBox).isChecked,
                        action = CartAction.Action.SELECT_SINGLE
                    )
                    viewModel.updateCartListLiveData(cartAction)
                }
                R.id.ivGoodsCartDelete -> {
                    AlertDialog.Builder(requireContext())
                        .setMessage("是否从购物车删除？")
                        .setPositiveButton(("确定")) { dialog, _ ->
                            viewModel.cartRemove(itemData.goods_id, itemData.cart_id)
                            dialog.cancel()
                        }.setNegativeButton(("取消"), (null)).show()
                }
                R.id.flGoodsCartPlus -> {
                    val goodsNum = itemData.goods_num + 1
                    viewModel.cartChangeNum1(
                        itemData.goods_id, itemData.cart_id, goodsNum, itemData.isSelected
                    )
                }
                R.id.flGoodsCartReduce -> {
                    val goodsNum = (itemData.goods_num - 1)
                    if (goodsNum == 0) {
                        AlertDialog.Builder(requireContext())
                            .setMessage("是否从购物车删除？")
                            .setPositiveButton(("确定")) { dialog, _ ->
                                viewModel.cartRemove(itemData.goods_id, itemData.cart_id)
                                dialog.cancel()
                            }.setNegativeButton(("取消"), (null)).show()
                    } else {
                        viewModel.cartChangeNum1(
                            itemData.goods_id, itemData.cart_id, goodsNum, itemData.isSelected
                        )
                    }
                }
            }
        }


        tvCartGoodsLocal.text = JCApplication.userShops?.shop_name
        //位置地址
        tvCartGoodsLocal.setOnClickListener {
            MineShopsActivity.open()
        }

        //清空购物车
        tvCartGoodsClear.setOnClickListener {
            val cartIds: Array<Int> =
                goodsCartAdapter.data.map { it.cart_id }.toTypedArray()
            AlertDialog.Builder(requireContext())
                .setMessage("您确定要清空购物车吗？")
                .setPositiveButton(("确定")) { dialog, _ ->
                    viewModel.cartClear(cartIds)
                    dialog.cancel()
                }.setNegativeButton(("取消"), (null)).show()
        }

        //全选
        cbCartGoodsAll.setOnClickListener {
            val cartAction = CartAction(
                isSelected = cbCartGoodsAll.isChecked,
                action = CartAction.Action.SELECT_ALL
            )
            viewModel.updateCartListLiveData(cartAction)
        }

        //去结算
        tvCartGoodsSettle.setOnClickListener {
            val cartIds: Array<Int> =
                goodsCartAdapter.data.filter { it.isSelected }
                    .map { it.cart_id }.toTypedArray()
            if (cartIds.isEmpty()) {
                toast("请选择商品结算")
            } else {
                viewModel.cartSettlement(cartIds)
            }
        }
    }

    override fun initData() {
        viewModel.cartIndex()
    }

    override fun onRefreshLoad() {
        viewModel.cartIndex()
    }

    override fun initViewMode() {
        viewModel.cartIndexLiveData.observe(this, Observer { response ->
            when (response.status) {
                Status.START -> {
                    goodsCartAdapter.setEmptyView(createLoadingView())
                }
                Status.SUCCESS -> {
                    goodsCartAdapter.removeEmptyView()
                }
                Status.FAILURE -> {
                    goodsCartAdapter.removeEmptyView()
                    toast(response.error?.msg)
                }
            }
        })

        viewModel.cartChangeNum1LiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.error?.msg)
            }
        })

        viewModel.cartDelete1LiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> {
                    LoadingDialog.show(requireContext(), resId = R.layout.dialog_load_style_1)
                }
                Status.SUCCESS -> response.data?.let {
                    LoadingDialog.dismiss()
                }
                Status.FAILURE -> {
                    toast(response.error?.msg)
                    LoadingDialog.dismiss()
                }
            }
        })

        viewModel.cartSettlementLiveData.observe(viewLifecycleOwner, Observer { response ->
            when (response.status) {
                Status.START -> {
                    LoadingDialog.show(requireContext(), resId = R.layout.dialog_load_style_1)
                }
                Status.SUCCESS -> response.data?.let {
                    LoadingDialog.dismiss()
                }
                Status.FAILURE -> {
                    toast(response.error?.msg)
                    LoadingDialog.dismiss()
                }
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            val data = response.data?.data
                ?: return@Observer
            val bundle = Bundle().apply {
                putSerializable(CartSettlementActivity.KEY_CART_SETTLEMENT, data)
            }
            ActivityUtils.startActivity(bundle, CartSettlementActivity::class.java)
        })

        AppConstance.cartListLiveData.observe(viewLifecycleOwner, Observer { cartLis ->
            if (cartLis != null) {
                fillDataVisibility(cartLis)
            } else {
                goodsCartAdapter.setEmptyView(createNullDataView())
            }
        })

    }

    private fun fillDataVisibility(cartList: MutableList<CartGoods>?) {

        val isSizeZero: Boolean = cartList?.size ?: 0 != 0
        clCartGoodsBottom.visibility =
            if (isSizeZero) View.VISIBLE else View.GONE
        tvCartGoodsClear.visibility =
            if (isSizeZero) View.VISIBLE else View.GONE

        goodsCartAdapter.setList(cartList)
        if (!isSizeZero) {
            goodsCartAdapter.setEmptyView(createNullDataView())
        }

        fillDataUndulate(cartList?.filter { it.isSelected }?.toMutableList())
    }

    private fun fillDataUndulate(selectedCartList: MutableList<CartGoods>?) {
        val selectedSize: Int = selectedCartList?.size ?: 0

        cbCartGoodsAll.isChecked =
            selectedSize == goodsCartAdapter.data.size && selectedSize != 0

        var num = 0
        var price = 0.00
        selectedCartList?.forEach {
            num += it.goods_num
            price += it.goods_num * it.goods_price.toDouble()
        }

        cbCartGoodsAll.text =
            if (selectedSize == 0) "全选" else "已选($num)"
        tvCartGoodsPrice.text = StringBuilder("￥")
            .append(DecimalFormat(("############0.00")).format(price))
    }


    private fun createLoadingView(): View {
        return layoutInflater.inflate(R.layout.dialog_load_style_2, null)
    }

    private fun createNullDataView(): View {
        return layoutInflater.inflate(R.layout.view_empty_error, null).apply {
            findViewById<TextView>(R.id.tvEmptyMessage).text = "购物车空空如也哦~"
        }
    }

    override fun onEventMainThread(any: Any) {
        if (any is UserShops) {
            initData()
        }
    }
}